﻿
#region Usings
using System;
using System.Text;
#endregion

namespace LongNet.Security
{
    /// <summary>
    /// Utility class for doing Vernam encryption
    /// </summary>
    public static class VernamEncryption
    {
        #region Public Static Functions

        /// <summary>
        /// Encrypts a string using Vernam encryption
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <param name="Key">Key to use (must be the same size as the input string)</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string Input, string Key)
        {
            return Process(Input, Key);
        }
        /// <summary>
        /// Decrypts a string using Vernam encryption
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <param name="Key">Key to use (must be the same size as the input string)</param>
        /// <returns>A decrypted string</returns>
        public static string Dencrypt(string Input, string Key)
        {
            return Process(Input, Key);
        }
        #endregion

        #region Private Static Functions

        /// <summary>
        /// Actually does the encryption/decryption
        /// </summary>
        private static string Process(string Input, string Key)
        {
            if (Input.Length != Key.Length)
            {
                throw new ArgumentException("Key is not the same length as the input string");
            }
            ASCIIEncoding Encoding = new ASCIIEncoding();
            byte[] InputArray = Encoding.GetBytes(Input);
            byte[] KeyArray = Encoding.GetBytes(Key);
            byte[] OutputArray = new byte[InputArray.Length];
            for (int x = 0; x < InputArray.Length; ++x)
            {
                OutputArray[x] = (byte)(InputArray[x] ^ Key[x]);
            }
            return Encoding.GetString(OutputArray);
        }

        #endregion
    }
}